<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
//        'partner' => '2088621781822784',//用不着
//        'seller_id' => 'admin@bagepanzi.com',//用不着
//        'sign_type' => 'RSA2',// 直接写死了
//        'it_b_pay' => '10m',//用不着
//        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'appId' => '2021001106648596',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAprbu7qO5M1Uz8XTi4lakVJrbqGK//GXIIjINVvKz9ijNPGCXT3OX8kglHfbBDneaKklLBcobyUo5BckIRGqmV2r+V1Wl9KHGtQTLKIMiL1Fw4mZgQWQh6v2neZqkxd/EHcfdb3PwIO0mJkkazoFm9iW20vC+z8yIpjSONTkkuOotMu5W3GIJEjw00x8p9qEgzXNoHgFH3i4CL9+1rlBH2GALvTIHluqMw9MRXrYBKRqgneRm1qkd5sSnYRekRvpCI3jOm5azsNv/CTYkpZPXzNjMkCIC27Bnuug0A31DPtLVr6wEa5oZA1WObnYscokXVaiUs6VuZZJhybVw3d4SoQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt4mMPlKh82QPLMHSDOKLUXiltBrrXdzsAIDujOU+LVB3UU6ibkdacev89Q5IIHjGTThuL6zgF2ut0F03e/HCpkksrHA7HCVXuFYQPIEBeUEB7qTGkAJz6ybydw/xitI60pJMs+aoT8pPcrgipyuVrTzGgQEDa2E+/rv9omPd5C54Gp8fSSYd3FeveBV3wrCyDlX/UWBNlQnu9TltqiY1PfgnhI/oUoyi5LvXmNgfODafrA3Sguwq74TihvHmcqGVxroXg5KZFIgnWmRRfpcpBoz4E+8rlIpa9hGFYKGmnQm1b9tvPj/klep+0W8xzVPOTCm+9nb4dAQ6gcKf2xhhDQIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAt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59Zor4XsvnRZOuBnGUO+VbmY/3sbW7PHGWJTOGTw8toEpeadqDA8qDhO/s3u+JZc+zHiFX60E02MTuOL89kHLVEWCN8SFlvP3FxA7LvNx9ONb7EOrErfBi2YnQmEZoy4a8iLpqNRYxqoSECgYBLo0knaPREKFVK2ADrq9mJ79+GUsW/ToNl0i5LKCAm2FeR84Ov4Zk3DarpBZpisKidfhyz+Sj6QGvFlNkJhw1lhY5qJrXQN17BoZyXUXLre9g3vK/I+HgwT7Hf0bcjDq2WZwLabwRqH1Mc9afr8HTYrCtrJI9ef0MFGjuJ35AFkQKBgFc0hIV5ItVgITzIJY5dfbC4Om8Xvtl9wkZzbJ7MgpQqDcPFjZDpLxkrtPjkakMYdppHZ7qnsouw4PBs4IZVJeAewiLlyKUHA/LJHrQOjFyYwWSDbm+HxZJUGujgqYtItEF/ADvbaoPS3cYuLGBbmqKtJYAboJjsO/UkIW21h6sj'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = $this->config['appId'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://car.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    
    /**
     * 生成订单
     * @return \think\response\Json
     * order_id   订单ID
     */
    public function alipay()
    {
        $params = input('');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        
        // 更新支付方式
        $result = Db::table('up_order')
            ->where('order_id', $params['order_id'])
            ->update(['order_pay_type' => 1, 'order_type_choose_time' => date('Y-m-d H:i:s')]);
        
        // 插入数据库成功，调起支付，否则返回错误
        if($result){
            $order_info = Db::table('up_order')
                ->field('order_number, order_price')
                ->where('order_id', $params['order_id'])
                ->find();
            $this->body = '联合卡车';
            $this->subject = '联合卡车';
            $this->total_amount = $order_info['order_price'];
//            $this->total_amount = 0.01;
            $this->out_trade_no = $order_info['order_number'];
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            $respont['order_id'] = $params['order_id'];
            return json_encode($respont);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try{
                    $num = $getInfo['out_trade_no'];//订单号
                    // 更新订单
                    $update = [
                        'order_status' => 2,
                        'order_pay_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_order')->where('order_number', $num)->update($update);
    
                    // 增加销量
                    $order_info = Db::table('up_order')
                        ->where('order_number', $num)
                        ->field('order_num, order_goods_id, order_id, order_user_id')
                        ->find();
                    Db::table('up_goods')->where('goods_id', $order_info['order_goods_id'])->setInc('goods_sale_num', $order_info['order_num']);
                    
                    // 消息表
                    $title = '订单支付成功，点击查看详情';
                    $notice = [
                        'notice_type' => 2,
                        'notice_cate' => 1,
                        'notice_subject_id' => $order_info['order_id'],
                        'notice_title' => $title,
                        'notice_user' => ',0,' . $order_info['order_user_id'] . ',',
                        'notice_read_user' => ',0,',
                        'notice_del_user' => ',0,',
                        'notice_time' => date('Y-m-d H:i:s'),
                    ];
                    Db::table('up_notice')->insert($notice);
                    
                    // 推送
                    $send_user = (string)$order_info['order_user_id'];
                    try{
                        $this->Jpush(1, $send_user, $title, ['send_type' => 3, 'order_id' => $order_info['order_id']]);
                    }catch(\Exception $e){
                        
                    }
                    
                    Db::commit();
                    return 'success';
                }catch(\Exception $e){
                    Db::rollback();//回滚
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->config['appId'];
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}